<?php
//配置调用接口
class jssdk extends Control {
  private $appId = 'wx0f8f93032bdd8579';
  private $appSecret = 'c8f0eba267a9b38a0175002a5923810e';

  public function _GET(){
    //获取签名包
    session_start();
    $gid = $_SESSION['id'];

    $access_token = $this->getAccessToken();
    $data = $this->GetSignPackage();
    $image = $this->sql('huodong.wx_ceshi')->select('*')->where(['id ='=>$gid])->query();
    if ($image) {
      $data['image'] = $image[0]['shareimg'];
      $data['gid'] = $gid;

      $this->display('sign',$data);
    }
  }
  
  //上传图片获取服务器ID
  public function test_GET(){
      $serverId = $_POST['serverId'];
      $token = $this->getAccessToken();
      $urls = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token='.$token.'&media_id='.$serverId;
      $rt = curl_do($urls);
      $rt = $rt[1];
      $gid = $_POST['gid'];//????
      $str = $gid.substr(time(), -6).'.jpg';//给图片命名及格式
      $strs = '/images/tmp/'.$str;//存在服务器目录/images/tmp/下，
      $upimages = file_put_contents($strs, $rt);//将文件$rt写入路径$strs中
      if ($upimages) {
         $data['shareimg'] = 'http://img1.nb85.cn/tmp/'.$str;//服务器路径可查看分享的图片
         $this->sql('huodong.wx_ceshi')->update($data)->where(['id='=>$gid])->query();//???
         echo json_encode(array('status'=>0,'msg'=>$str));
      }else{
         echo json_encode(array('status'=>1,'msg'=>'上传失败'));
      }     
  }



  //获取签名
    public function GetSignPackage() {
      $jsapiTicket = $this->getJsApiTicket();
      $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";//server_port,服务器端口443，网页浏览端口，能提供加密和通过安全端口传输的另一种HTTP。
      $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";//请求头信息中的Host内容，获取当前域名。当前脚本路径，根目录之后的目录。
      $timestamp = time();
      $nonceStr = $this->createNonceStr();

      // 这里参数的顺序要按照 key 值 ASCII 码升序排序
      $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
      $signature = sha1($string);
      $signPackage = array(
        "appId"     => $this->appId,
        "nonceStr"  => $nonceStr,
        "timestamp" => $timestamp,
        "url"       => $url,
        "signature" => $signature,
        "rawString" => $string
      );
      return $signPackage; 
    }
   
    //获取随机字符串
    public function createNonceStr($length = 16) {
      $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      $str = "";
      for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
      }
      return $str;
    }


    //获取jsapiticket
    public function getJsApiTicket() {
        $data = $this->red('cache')->get('appId_jsapi_ticket');

        if ($data !== false) {
            $data = json_decode($data,true);
            if ($data['expire_time'] < time()) {   //判断过期时间     
                  $accessToken = $this->getAccessToken();
                  $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
                  $res = json_decode($this->httpGet($url));
                $ticket = $res->ticket;
                  if ($ticket) {
                    $expire_time = 7000;
                    $data['expire_time'] = time() + $expire_time;
                    $expire_time = $data['expire_time'];
                    $data['jsapi_ticket'] = $ticket;
                    $this->red('cache')->setex('appId_jsapi_ticket',$expire_time,json_encode($data,true));
                  }
            }else{
                $data['expire_time'] = $data['expire_time'];
                $data['jsapi_ticket'] = $data['jsapi_ticket'];
            }
        }else{
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
              $expire_time = 7000;
              $data['expire_time'] = time() + $expire_time;
              $data['jsapi_ticket'] = $ticket;
              $this->red('cache')->setex('appId_jsapi_ticket',$expire_time,json_encode($data,true));
            }        
         
        }
        return $data['jsapi_ticket'];
   }
      //获取accesstoken
      public function getAccessToken(){
          $data = $this->red('cache')->get('appId_access_token');
          if ($data !== false){
              $data = json_decode($data,true);
              if ($data['expire_time'] < time()){
                  $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
                  $res = json_decode($this->httpGet($url));
                  $access_token = $res->access_token;  //
                  if ($access_token) {
                    $expire_time = 7000;
                    $data['expire_time'] = time() + $expire_time;
                    $data['access_token'] = $access_token;   //
                    //$this->set_php_file("access_token.php", json_encode($data));   
                    $this->red('cache')->setex('appId_access_token',$expire_time,json_encode($data,true));
                  }
              }else{
                   $data['expire_time'] = $data['expire_time'];
                   $data['access_token'] = $data['access_token'];
              }
          }else{
                 //return  $this->refreshAccessToken();
              $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
              $res = json_decode($this->httpGet($url));
              $access_token = $res->access_token;  //
              if ($access_token) {
                $expire_time = 7000;
                $data['expire_time'] = time() + $expire_time;
                $data['access_token'] = $access_token;   //
                //$this->set_php_file("access_token.php", json_encode($data));   
                $this->red('cache')->setex('appId_access_token',$expire_time,json_encode($data,true));
              }
          }
          return $data['access_token'];
        }
    //curl函数   https的接口调用
      public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  //curlopt_returntransfer属性将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);   //curlopt_timeout,500，设置cURL允许执行的最长秒数
        curl_setopt($curl, CURLOPT_URL, $url);    //curlopt_url，，需要获取的URL地址，也可以在curl_init()函数中设置
        $res = curl_exec($curl);//执行给定的cURL会话。
        curl_close($curl);//关闭curl，释放资源
        return $res;
      }
}

